/**
 * Notes: 研发项目控制器
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2023-08-30 19:20:00
 */

const BaseProjectController = require('./base_project_controller.js');
const ResearchModel = require('../model/research_model.js');
const ResearchProjectModel = require('../model/research_project_model.js');
const ResearchResourceModel = require('../model/research_resource_model.js');
const ResearchStateHistoryModel = require('../model/research_state_history_model.js');
const util = require('../../../framework/helpers/util.js');
const timeUtil = require('../../../framework/helpers/time_util.js');
const cloudUtil = require('../../../framework/cloud/cloud_util.js');
const cloudBase = require('../../../framework/cloud/cloud_base.js');

class ResearchController extends BaseProjectController {

	/** 获取研发项目列表 */
	async getResearchList() {
		// 数据校验
		let rules = {
			search: 'string|min:1|max:30|name=搜索条件',
			sortType: 'string|name=搜索类型',
			sortVal: 'name=搜索类型值',
			orderBy: 'object|name=排序',
			page: 'must|int|default=1',
			size: 'int|default=10',
			isTotal: 'bool',
			oldTotal: 'int',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = {};
		let result = await ResearchModel.getList(service, input);

		// 数据格式化
		let list = result.list;
		for (let i = 0; i < list.length; i++) {
			list[i].RESEARCH_ADD_TIME = timeUtil.timestamp2Time(list[i].RESEARCH_ADD_TIME, 'Y-M-D h:m:s');
		}

		return result;
	}

	/** 获取研发项目详情 */
	async getResearchDetail() {
		// 数据校验
		let rules = {
			id: 'must|id',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = {};
		let research = await ResearchModel.getOne(service, input.id);
		if (research) {
			research.RESEARCH_ADD_TIME = timeUtil.timestamp2Time(research.RESEARCH_ADD_TIME, 'Y-M-D h:m:s');
		}

		return research;
	}

	/** 获取项目图谱 */
	async getProjectGraph() {
		// 数据校验
		let rules = {
			id: 'must|id',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = {};
		let research = await ResearchModel.getOne(service, input.id);
		
		if (!research) {
			this.appError('项目不存在');
		}

		// 获取项目状态结构图
		let graph = {
			nodes: [
				{
					id: 'planning',
					label: '规划阶段',
					status: 10,
					x: 100,
					y: 100
				},
				{
					id: 'design',
					label: '设计阶段',
					status: 20,
					x: 200,
					y: 100
				},
				{
					id: 'development',
					label: '开发阶段',
					status: 30,
					x: 300,
					y: 100
				},
				{
					id: 'testing',
					label: '测试阶段',
					status: 40,
					x: 400,
					y: 100
				},
				{
					id: 'review',
					label: '评审阶段',
					status: 50,
					x: 500,
					y: 100
				},
				{
					id: 'completed',
					label: '已完成',
					status: 60,
					x: 600,
					y: 100
				}
			],
			edges: [
				{
					source: 'planning',
					target: 'design',
					label: '提交设计'
				},
				{
					source: 'design',
					target: 'development',
					label: '提交开发'
				},
				{
					source: 'development',
					target: 'testing',
					label: '提交测试'
				},
				{
					source: 'testing',
					target: 'review',
					label: '提交评审'
				},
				{
					source: 'review',
					target: 'completed',
					label: '完成'
				}
			],
			currentNode: 'planning'
		};

		// 根据项目当前状态设置当前节点
		if (research.PROJECT_STATUS) {
			switch (research.PROJECT_STATUS) {
				case 10:
					graph.currentNode = 'planning';
					break;
				case 20:
					graph.currentNode = 'design';
					break;
				case 30:
					graph.currentNode = 'development';
					break;
				case 40:
					graph.currentNode = 'testing';
					break;
				case 50:
					graph.currentNode = 'review';
					break;
				case 60:
					graph.currentNode = 'completed';
					break;
				default:
					graph.currentNode = 'planning';
			}
		}

		return graph;
	}

	/** 获取项目状态路径 */
	async getResearchStatePath() {
		// 数据校验
		let rules = {
			id: 'must|id',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = {};
		let research = await ResearchModel.getOne(service, input.id);
		
		if (!research) {
			this.appError('项目不存在');
		}

		// 获取项目状态路径
		let statePath = {
			steps: [
				{
					id: 'planning',
					name: '规划阶段',
					status: 10,
					activeStatus: [11, 12, 13],
					subSteps: [
						{
							id: 'plan_draft',
							name: '草稿',
							status: 10,
							activeStatus: 11
						},
						{
							id: 'plan_review',
							name: '评审中',
							status: 10,
							activeStatus: 12
						},
						{
							id: 'plan_approved',
							name: '已批准',
							status: 10,
							activeStatus: 13
						}
					]
				},
				{
					id: 'design',
					name: '设计阶段',
					status: 20,
					activeStatus: [21, 22, 23],
					subSteps: [
						{
							id: 'design_draft',
							name: '草稿',
							status: 20,
							activeStatus: 21
						},
						{
							id: 'design_review',
							name: '评审中',
							status: 20,
							activeStatus: 22
						},
						{
							id: 'design_approved',
							name: '已批准',
							status: 20,
							activeStatus: 23
						}
					]
				},
				{
					id: 'development',
					name: '开发阶段',
					status: 30,
					activeStatus: [31, 32, 33],
					subSteps: [
						{
							id: 'dev_ongoing',
							name: '进行中',
							status: 30,
							activeStatus: 31
						},
						{
							id: 'dev_review',
							name: '评审中',
							status: 30,
							activeStatus: 32
						},
						{
							id: 'dev_completed',
							name: '已完成',
							status: 30,
							activeStatus: 33
						}
					]
				},
				{
					id: 'testing',
					name: '测试阶段',
					status: 40,
					activeStatus: [41, 42, 43],
					subSteps: [
						{
							id: 'test_ongoing',
							name: '进行中',
							status: 40,
							activeStatus: 41
						},
						{
							id: 'test_failed',
							name: '未通过',
							status: 40,
							activeStatus: 42
						},
						{
							id: 'test_passed',
							name: '已通过',
							status: 40,
							activeStatus: 43
						}
					]
				},
				{
					id: 'review',
					name: '评审阶段',
					status: 50,
					activeStatus: [51, 52, 53],
					subSteps: [
						{
							id: 'review_ongoing',
							name: '进行中',
							status: 50,
							activeStatus: 51
						},
						{
							id: 'review_failed',
							name: '未通过',
							status: 50,
							activeStatus: 52
						},
						{
							id: 'review_passed',
							name: '已通过',
							status: 50,
							activeStatus: 53
						}
					]
				},
				{
					id: 'completed',
					name: '已完成',
					status: 60,
					activeStatus: [60],
					subSteps: [
						{
							id: 'completed',
							name: '已完成',
							status: 60,
							activeStatus: 60
						}
					]
				}
			],
			currentStep: 'planning',
			currentSubStep: 'plan_draft'
		};

		// 根据项目当前状态设置当前节点
		if (research.PROJECT_STATUS) {
			switch (research.PROJECT_STATUS) {
				case 10:
					statePath.currentStep = 'planning';
					break;
				case 20:
					statePath.currentStep = 'design';
					break;
				case 30:
					statePath.currentStep = 'development';
					break;
				case 40:
					statePath.currentStep = 'testing';
					break;
				case 50:
					statePath.currentStep = 'review';
					break;
				case 60:
					statePath.currentStep = 'completed';
					break;
				default:
					statePath.currentStep = 'planning';
			}
		}

		// 根据活动状态设置当前子步骤
		if (research.PROJECT_ACTIVE_STATUS) {
			for (let step of statePath.steps) {
				for (let subStep of step.subSteps) {
					if (subStep.activeStatus === research.PROJECT_ACTIVE_STATUS) {
						statePath.currentSubStep = subStep.id;
						break;
					}
				}
			}
		}

		return statePath;
	}

	/** 项目状态流转 */
	async transitProjectState() {
		// 数据校验
		let rules = {
			id: 'must|id',
			targetStatus: 'must|int',
			targetActiveStatus: 'must|int',
			note: 'string|max:200|name=备注',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = {};
		let research = await ResearchModel.getOne(service, input.id);
		
		if (!research) {
			this.appError('项目不存在');
		}

		// 执行状态流转 - 使用新的状态字段
		let data = {
			level1: input.targetStatus,
			level3: input.targetActiveStatus,
			STATUS_UPDATE_TIME: timeUtil.time(),
			PROJECT_EDIT_TIME: timeUtil.time()
		};

		let result = await ResearchModel.edit(service, input.id, data);

		// 记录状态流转历史 - 使用新的状态字段名称存储历史记录
		let historyData = {
			HISTORY_PROJECT_ID: input.id,
			HISTORY_LEVEL1: input.targetStatus,
			HISTORY_LEVEL3: input.targetActiveStatus,
			HISTORY_NOTE: input.note || '',
			HISTORY_USER_ID: service.OPENID,
			HISTORY_ADD_TIME: timeUtil.time()
		};

		await ResearchStateHistoryModel.insert(service, historyData);

		return result;
	}

	/** 获取资源列表 */
	async getResourceList() {
		// 数据校验
		let rules = {
			projectId: 'must|id',
			search: 'string|min:1|max:30|name=搜索条件',
			sortType: 'string|name=搜索类型',
			sortVal: 'name=搜索类型值',
			orderBy: 'object|name=排序',
			page: 'must|int|default=1',
			size: 'int|default=10',
			isTotal: 'bool',
			oldTotal: 'int',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = {};
		
		// 查询条件设置
		let whereConst = {
			RESOURCE_PROJECT_ID: input.projectId
		};

		let result = await ResearchResourceModel.getList(service, whereConst, input);

		// 数据格式化
		let list = result.list;
		for (let i = 0; i < list.length; i++) {
			list[i].RESOURCE_ADD_TIME = timeUtil.timestamp2Time(list[i].RESOURCE_ADD_TIME, 'Y-M-D h:m:s');
		}

		return result;
	}

	/** 创建资源 */
	async createResource() {
		// 数据校验
		let rules = {
			projectId: 'must|id',
			name: 'must|string|min:2|max:50|name=资源名称',
			type: 'must|int|in:1,2,3,4,99|name=资源类型',
			url: 'must|string|min:5|max:500|name=资源链接',
			desc: 'string|max:200|name=资源描述',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = {};
		let data = {
			RESOURCE_PROJECT_ID: input.projectId,
			RESOURCE_NAME: input.name,
			RESOURCE_TYPE: input.type,
			RESOURCE_URL: input.url,
			RESOURCE_DESC: input.desc || '',
			RESOURCE_ADD_TIME: timeUtil.time()
		};

		let result = await ResearchResourceModel.insert(service, data);

		return result;
	}

	/** 获取状态流转历史 */
	async getStateHistory() {
		// 数据校验
		let rules = {
			projectId: 'must|id',
			page: 'must|int|default=1',
			size: 'int|default=10',
			isTotal: 'bool',
			oldTotal: 'int',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = {};
		
		// 查询条件设置
		let whereConst = {
			HISTORY_PROJECT_ID: input.projectId
		};

		let result = await ResearchStateHistoryModel.getList(service, whereConst, input);

		// 数据格式化
		let list = result.list;
		for (let i = 0; i < list.length; i++) {
			list[i].HISTORY_ADD_TIME = timeUtil.timestamp2Time(list[i].HISTORY_ADD_TIME, 'Y-M-D h:m:s');
		}

		return result;
	}

	/**
	 * 添加研发项目 
	 */
	async insertResearch() {
		// 数据校验
		let rules = {
			customerName: 'string|min:2|max:50|name=客户名称',
			projectType: 'string|min:2|max:100|name=项目类型',
			model: 'string|max:50|name=型号',
			priority: 'array|name=优先级',
			description: 'string|max:5000|name=项目详情',
			applicationType: 'string|max:50|name=应用类型',
			startDate: 'int|name=开始日期',
			deadline: 'int|name=截止日期',
			hasSample: 'string|max:10|name=有无样品',
			sampleCount: 'string|max:20|name=样品数量',
			sampleImages: 'array|name=样品图片'
		};

		// 取得数据
		let input = this.validateData(rules);

		// 检查用户权限（可选，根据需求增加额外的权限检查）
		const now = Math.floor(Date.now() / 1000);
		
		// 构建请求数据
		const projectData = {
			projectType: input.projectType || '',
			model: input.model || `PRJ-${timeUtil.time('YMD')}-${Math.floor(Math.random() * 1000).toString().padStart(3, '0')}`,
			
			// 分类与描述信息
			applicationType: input.applicationType || '',
			category: '研发',
			description: input.description || '',
			
			// 客户信息和申请人信息
			customerName: input.customerName || '',
			applicantId: this._openId,
			applicantName: input.applicantName || '',
			
			// 项目状态信息 - 初始状态为审批中
			level1: 1, // 审批中
			level2: 'director', // 董事长审批
			level3: '', 
			level4: '',
			statusDesc: '项目审核 > 董事长',
			priority: input.priority || 'normal',
			
			// 时间信息
			createTime: now,
			updateTime: now,
			stateTime: now,
			
			// 项目时间点
			startDate: input.startDate || now,
			deadline: input.deadline || (now + 30 * 24 * 60 * 60), // 默认30天后截止
			planStartDate: input.startDate || now,
			planEndDate: input.deadline || (now + 30 * 24 * 60 * 60),
			
			// 样品信息
			hasSample: input.hasSample || '无',
			sampleCount: input.sampleCount || '',
			sampleImages: input.sampleImages || []
		};
		
		// 根据应用类型设置项目类型
		if (input.applicationType) {
			const ResearchProjectModel = require('../model/research_project_model');
			const appTypeMapping = {
				'磁编': 1,
				'霍尔': 1,
				'风机': 1,
				'水泵': 1,
				'电源': 2,
				'传感器': 3,
				'其他': 4
			};
			
			const projectTypeNames = {
				1: '电机控制类',
				2: '电源类',
				3: '传感器类',
				4: '其他类型'
			};
			
			projectData.projectType = appTypeMapping[input.applicationType] || 4;
			projectData.projectTypeName = projectTypeNames[projectData.projectType] || '其他类型';
		}

		// 插入数据库
		const service = {};
		let result = await ResearchProjectModel.insert(service, projectData);

		return {
			id: result.id
		};
	}
}

module.exports = ResearchController; 